import React from 'react';
import { View, ScrollView } from 'react-native';
import { Text } from '@/components/ui/text';
import { Icon } from '@/components/ui/icon';
import { Phone, Clock, DollarSign, User, Bot } from 'lucide-react-native';
import type { ToolViewProps } from '../types';
import { extractCallStatusData, formatPhoneNumber, formatDuration, statusConfig } from './_utils';
import { ToolViewCard, StatusBadge, LoadingState } from '../shared';
import { getToolMetadata } from '../tool-metadata';

// Utility functions
function formatTimestamp(isoString?: string): string {
  if (!isoString) return '';
  try {
    const date = new Date(isoString);
    return isNaN(date.getTime()) ? 'Invalid date' : date.toLocaleString();
  } catch (e) {
    return 'Invalid date';
  }
}

export function CallStatusToolView({ toolCall, toolResult, isStreaming = false, assistantTimestamp, toolTimestamp }: ToolViewProps) {
  const data = extractCallStatusData({ toolCall, toolResult });

  if (!toolCall) {
    return null;
  }

  const name = toolCall.function_name.replace(/_/g, '-').toLowerCase();
  const toolMetadata = getToolMetadata(name, toolCall.arguments);
  const actualIsSuccess = toolResult?.success !== undefined ? toolResult.success : true;

  const statusInfo = statusConfig[data.status as keyof typeof statusConfig] || statusConfig.queued;

  if (isStreaming) {
    return (
      <ToolViewCard
        header={{
          icon: toolMetadata.icon,
          iconColor: toolMetadata.iconColor,
          iconBgColor: toolMetadata.iconBgColor,
          subtitle: toolMetadata.subtitle.toUpperCase(),
          title: toolMetadata.title,
          isSuccess: actualIsSuccess,
          isStreaming: true,
          rightContent: <StatusBadge variant="streaming" label="Fetching" />,
        }}
      >
        <View className="flex-1 w-full">
          <LoadingState
            icon={toolMetadata.icon}
            iconColor={toolMetadata.iconColor}
            bgColor={toolMetadata.iconBgColor}
            title="Fetching Call Status"
            showProgress={false}
          />
        </View>
      </ToolViewCard>
    );
  }

  return (
    <ToolViewCard
      header={{
        icon: toolMetadata.icon,
        iconColor: toolMetadata.iconColor,
        iconBgColor: toolMetadata.iconBgColor,
        subtitle: toolMetadata.subtitle.toUpperCase(),
        title: toolMetadata.title,
        isSuccess: actualIsSuccess,
        isStreaming: false,
        rightContent: (
          <StatusBadge
            variant={actualIsSuccess ? 'success' : 'error'}
            label={statusInfo.label}
          />
        ),
      }}
      footer={
        <View className="flex-row items-center justify-between w-full">
          {data.phone_number && (
            <Text className="text-xs text-muted-foreground flex-1" numberOfLines={1}>
              {formatPhoneNumber(data.phone_number)}
            </Text>
          )}
          {(toolTimestamp || assistantTimestamp) && (
            <Text className="text-xs text-muted-foreground ml-2">
              {toolTimestamp ? formatTimestamp(toolTimestamp) : assistantTimestamp ? formatTimestamp(assistantTimestamp) : ''}
            </Text>
          )}
        </View>
      }
    >
      <ScrollView className="flex-1 w-full" showsVerticalScrollIndicator={false}>
        <View className="px-4 py-4 gap-6">
          <View className="flex-row gap-2">
            {data.duration_seconds !== undefined && (
              <View className="bg-muted/30 rounded-xl p-3 border border-border flex-1">
                <View className="flex-row items-center gap-2 mb-1">
                  <Icon as={Clock} size={14} className="text-muted-foreground" />
                  <Text className="text-xs font-roobert-medium text-muted-foreground">Duration</Text>
                </View>
                <Text className="text-lg font-roobert-semibold text-foreground">
                  {formatDuration(data.duration_seconds)}
                </Text>
              </View>
            )}

            {data.cost !== undefined && (
              <View className="bg-muted/30 rounded-xl p-3 border border-border flex-1">
                <View className="flex-row items-center gap-2 mb-1">
                  <Icon as={DollarSign} size={14} className="text-muted-foreground" />
                  <Text className="text-xs font-roobert-medium text-muted-foreground">Cost</Text>
                </View>
                <Text className="text-lg font-roobert-semibold text-foreground">
                  ${data.cost.toFixed(2)}
                </Text>
              </View>
            )}
          </View>

          {data.transcript && data.transcript.length > 0 && (
            <View className="gap-3">
              <Text className="text-sm font-roobert-medium text-foreground/70">
                Transcript ({data.transcript.length} messages)
              </Text>
              <View className="gap-2">
                {data.transcript.map((msg, idx) => (
                  <View
                    key={idx}
                    className={`rounded-xl p-3 ${msg.role === 'assistant'
                      ? 'bg-primary/10 ml-4'
                      : 'bg-muted/50 mr-4'
                      }`}
                  >
                    <View className="flex-row items-center gap-2 mb-1">
                      <Icon
                        as={msg.role === 'assistant' ? Bot : User}
                        size={12}
                        className="text-muted-foreground"
                      />
                      <Text className="text-xs font-roobert-medium text-muted-foreground">
                        {msg.role === 'assistant' ? 'AI' : 'Caller'}
                      </Text>
                    </View>
                    <Text className="text-sm font-roobert text-foreground">
                      {msg.message}
                    </Text>
                  </View>
                ))}
              </View>
            </View>
          )}
        </View>
      </ScrollView>
    </ToolViewCard>
  );
}
